package io.gitee.twoke.generator.engine.impl.cmd;

import io.gitee.twoke.generator.engine.impl.interceptor.Command;
import io.gitee.twoke.generator.engine.impl.interceptor.CommandContext;
import io.gitee.twoke.generator.engine.impl.persistence.entity.TemplateEntity;
import io.gitee.twoke.generator.engine.impl.persistence.entity.TemplateEntityManager;
import io.gitee.twoke.generator.engine.impl.persistence.entity.TemplateFileEntity;
import io.gitee.twoke.generator.engine.impl.persistence.entity.TemplateFileEntityManager;
import io.gitee.twoke.generator.engine.impl.template.Template;
import io.gitee.twoke.generator.engine.impl.template.impl.CreateTemplateBuilderImpl;

import java.util.List;

public class CreateTemplateCmd implements Command<Template> {

    private CreateTemplateBuilderImpl templateBuilder;

    public CreateTemplateCmd(CreateTemplateBuilderImpl templateBuilder) {
        this.templateBuilder = templateBuilder;
    }

    @Override
    public Template execute(CommandContext commandContext) {
        TemplateEntity templateEntity = insertTemplate(commandContext.getTemplateEntityManager());
        insertTemplateFiles(templateEntity.getId(),commandContext.getTemplateFileEntityManager());
        return templateEntity;
    }

    private void insertTemplateFiles(String templateId, TemplateFileEntityManager manager) {
        List<TemplateFileEntity> templateFileEntities = templateBuilder.getTemplateFileEntities();
        if (templateFileEntities.isEmpty()) return;
        templateFileEntities.forEach(tplFile -> {
            tplFile.setTemplateId(templateId);
            manager.insert(tplFile);
        });
    }

    private TemplateEntity insertTemplate( TemplateEntityManager manager) {
        TemplateEntity template = templateBuilder.getTemplate();
        manager.insert(template);
        return template;
    }


}
